<template>
	<view>
		<view class="container">
		    <!-- 页面的主体内容 -->
		    <view class="content">
				<uni-section title="控制器" type="line">
					
					<template v-slot:right>
	 
						<uni-tag v-if="shipInfo?.controlMode==1" text="JT" type="success" size="mini" circle="true"/>
						<uni-tag v-if="!shipInfo?.controlMode" text="RC" type="success" size="mini" circle="true"/>
						<span class="pd">电压：<uni-tag :text="shipInfo.batteryVoltage/100+'V'" :type="shipInfo.batteryVoltage<1120?'error':'success'" size="mini" circle="true"/></span>
						
						<uni-tag v-if="heatBeat" text="心跳" type="success" size="mini" circle="true"/>
						<uni-tag v-if="!heatBeat" text="心跳" type="error" size="mini" circle="true"/>
					</template>
					
					<view class="video-ctr">
					  <div id="aliyunVideo"></div>
					</view>
					
					<wd-grid clickable>
						<wd-grid-item :icon="jetsonInfo?.tracking==1?'lock-on':'lock-off'" :text="jetsonInfo?.tracking==1?'锁定':'解锁'" @click="lock_fp()"/>
						<wd-grid-item :icon="shipInfo?.rodStatus==1?'slash':'decrease'" :text="shipInfo?.rodStatus==1?'抬起':'放下'" @click="rod_up()"/>
						<wd-grid-item :icon="shipInfo?.fishWireStatus==0?'stop-circle':(shipInfo?.fishWireStatus==1?'arrow-right1':'rollback')" :text="shipInfo?.fishWireStatus==0?'停止':(shipInfo?.fishWireStatus==1?'放线':'收线')" @click="fish_wire_show()"/>
					</wd-grid>

				</uni-section>
				
				<uni-row class="ctl-wrapper" :animation="animationData">
					<view class="ctl">
						<view id="controllerZone"></view>
					</view>
				</uni-row>
		    </view>
			
			
			
		    <!-- 固定在底部的底部组件 -->
		    <view class="fixed-footer">
		      <uni-grid :column="3">
		      	<uni-grid-item @click="start()">
		      		<uni-icons type="navigate" size="60"></uni-icons>
		      		<text>开始</text>
		      	</uni-grid-item>
		      	<uni-grid-item>
					<span v-show="shipInfo?.controlMode==1">
						<uni-icons :type="shipInfo?.servoMotorDirection==0 ?'arrow-up':'arrow-down'" size="60" @click="servo()"></uni-icons>
<!-- 						<text>{{shipInfo?.servoMotorDirection==0 ? '舵机向前':'舵机向后'}}</text> -->
					</span>
		      		
		      	</uni-grid-item>
		      	<uni-grid-item @click="stop()">
		      		<uni-icons type="closeempty" size="60"></uni-icons>
		      		<text>暂停</text>
		      	</uni-grid-item>
		      </uni-grid>
		    </view>
		  </view>
		  

	</view>
	
	<wd-notify />
	<wd-action-sheet v-model="showEatAction" :actions="actionsEats" cancel-text="取消"/>
	
	<wd-popup v-model="showPopup" position="bottom" custom-style="height: 500px;">
		<wd-tabs v-model="popupTabIndex">
			<wd-tab title="参数配置">
			  <wd-cell title="灵敏度设置" vertical>
			    <wd-row>
					<wd-col :span="2">高</wd-col>
					<wd-col :span="20">
						<wd-slider v-model="fpSensitivity" @dragend="fpSliderGragEnd()" hide-min-max></wd-slider>
					</wd-col>
					<wd-col :span="2">低</wd-col>
				</wd-row>
			  </wd-cell>
			  <wd-cell title="自动钓鱼" center>
			      <view class="custom-value" style="height: 32px;">
			        <wd-switch v-model="shipInfo.autoFish" @change="handleSwitchAutoFishChange"/>
			      </view>
			  </wd-cell>
			</wd-tab>
		  <wd-tab title="姿态信息">
		    <uni-table>
		    	<uni-tr>
		    		<uni-td>Pitch</uni-td>
		    		<uni-td><wd-tag type="success" round>{{shipInfo.pitch}}</wd-tag></uni-td>
		    		<uni-td>Roll</uni-td>
		    		<uni-td><wd-tag type="success" round>{{shipInfo.roll}}</wd-tag></uni-td>
		    		<uni-td>Yaw</uni-td>
		    		<uni-td><wd-tag type="success" round>{{shipInfo.yaw}}</wd-tag></uni-td>
		    	</uni-tr>
		    </uni-table>
		  </wd-tab>
		  <wd-tab title="导航信息">
		    <view class="content"></view>
		  </wd-tab>
		  <wd-tab title="通道数据">
			<wd-card class="channel-data">
				<wd-row v-for="item in shipInfo?.rcData">
					<wd-col :span="18">
						<wd-progress :percentage="item/25" hide-text duration="0"/>
					</wd-col>
					<wd-col :span="4" class="channel-value">
						<wd-tag type="primary" plain>{{item}}</wd-tag>
					</wd-col>
				
				</wd-row>
			</wd-card>
		  </wd-tab>
		</wd-tabs>
	</wd-popup>
	
	
	<wd-popup v-model="popShowFishWire" position="center" custom-style="width:200px;" @close="handleClose_PopupFishWire">
		<view class="fish_wire_wrapper">
			<wd-grid square clickable :column="1">
			  <wd-grid-item icon="arrow-right1" text="放线" @click="fish_wire_status(1)">
				  
			  </wd-grid-item>
			  <wd-grid-item icon="rollback" text="收线" @click="fish_wire_status(2)">
				  
			  </wd-grid-item>
			</wd-grid>
 
		</view>
	</wd-popup>
	
</template>

<script>
 
	import * as piService from "@/services/PiService.js";
	import * as Constant from "@/utils/constant.js";
	import {getAuthorization} from '@/utils/auth';
	import mqtt from 'mqtt/dist/mqtt.js';
	import * as env from '@/env.js';
	import nipplejs from 'nipplejs';
	import AMapLoader from '@amap/amap-jsapi-loader';
	import * as gps from '@/utils/gps.js';
	import * as GPSHelper from '@/utils/GpsHelper.js';
	import { useNotify } from 'wot-design-uni';
 

	window._AMapSecurityConfig = {
	  securityJsCode: '630ed0d1d8f3da8c7a34375945113124' // '「申请的安全密钥」',
	}
	
 
	
	
	export default {
		 setup() {
			const { showNotify, closeNotify } = useNotify();
		    return {
		      showNotify
		    }
		  },
		data() {
			return {
				map:null,
				client:null,
				cmdTopic:'topic/unmannedship/cmd',
				
				topics:[
					'topic/unmannedship/heartbeat',
				'topic/unmannedship/data/gyro',
				'topic/unmannedship/data/gps',
				'topic/unmannedship/data/volt',
				'topic/unmannedship/data/info',
				'topic/unmannedship/data/jetson/info',
				],
				options:{
					clientId:'client_' + Math.random().toString(16).substr(2, 8),
					username:'admin',
					password:'root1234!'
				},
				gpsData:[],
				angle:0,
				throttle:0,
				manager:null,
				heatBeat: false,
				tmrHeartBeat: null,
				animation:null,
				animationData:{},
				aliyunVideoUrl:{
					artcUrl:null,
					rtmpUrl:null,
					flvUrl:null
				},
				player:null,
				shipInfo:{},
				jetsonInfo:{},
				showPopup:false,
				popupTabIndex:0,
				fpSensitivity:50,
				showEatAction:false,
				actionsEats:[
					{
						name: '收线',
						color: '#F5003D'
					},
					{
						name: '溜鱼',
						color: '#0083ff'
					}
				],
				switchAutoFish:false,
				popShowFishWire:false
			}
		},
		
		created() {

		 
			// 此处的端口为mqtt.js中的http端口，否则H5和手机连接不上mqtt服务器  
			this.client = mqtt.connect('ws://101.132.123.218:19001/mqtt',this.options);
	 
		 
			// // #ifdef MP-WEIXIN||APP-PLUS  
			// // 此处需要改成你的主机ip，并保证测试手机跟你的电脑处于同一个局域网 
			// this.client = mqtt.connect('mqtt://101.132.123.218:11883',this.options);
			// // #endif

 
			this.client.on('connect',e=>{
				console.log("连接成功");
				uni.showToast({  
					title:"连接成功",  
					duration:2000,  
					icon:"none"
				})
				
				for(let item of this.topics){
					this.client.subscribe(item, (err) => {
						if (!err) {
						  console.log("订阅成功:" + item);
						}
					})
				}
					
 
			})
			
			
			this.client.on("message", (topic, rawMsg) => {
				
				let msg = rawMsg.toString();
				if(topic===this.topics[0]){
					this.heatBeat = true;
				}else if(topic===this.topics[1]){
					let tmpGyro = eval(msg);
					// for(let i=0;i<tmpGyro.length;i++){
					// 	this.gyroData[i]=tmpGyro[i].toFixed(2);
					// }
				}else if(topic===this.topics[2]){
					console.log('##gps数据');
					this.gpsData = eval(msg);
					// let pos = gps.wgs_gcj_encrypts(this.gpsData[1],this.gpsData[0]);
					// console.log(pos);
					this.map.setZoomAndCenter(14,[this.gpsData[1],this.gpsData[0]]);
					
				}else if(topic===this.topics[3]){
				 
				}else if(topic===this.topics[4]){
					this.shipInfo = JSON.parse(msg);
					let bitData = this.shipInfo?.bitData;
	
					if(bitData != undefined && bitData != null){
						this.shipInfo.controlMode = ((bitData & (1 << 0)) >> 0);
						this.shipInfo.servoMotorDirection = ((bitData & (1 << 1)) >> 1);
						this.shipInfo.rodStatus	= ((bitData & (1 << 2)) >> 2);
						this.shipInfo.autoFish	= ( ((bitData & (1 << 3)) >> 3 ) == 1 ? true:false);
						this.shipInfo.fishWireStatus = ((bitData & (3 << 4)) >> 4);
					}
					
					
				}else if(topic===this.topics[5]){
					this.jetsonInfo = JSON.parse(msg);
					//console.log('##jetsonInfo,',this.jetsonInfo);
					if(this.jetsonInfo?.eated==1){
						this.showNotify('中鱼了！！！');
						this.showEatAction = true;
					}
				}
				
			})
		},
		onLoad(option) {
			
			this.animation = uni.createAnimation({
				duration:990,
				timingFunction: 'ease'
			})
			
			this.tmrHeartBeat = setInterval(()=>{
				this.heatBeat = false;
			},1500);
			
			this.loadAliyunVideoUrl().then(()=>{
				this.camera(true);
					
				setTimeout(()=>{
					this.createPlayer();
					this.createJxController();
				},500);
				
			})
			
			
			
			
			
			//this.initMap();
		},
		onUnload(){
			this.camera(false);
			console.log('#######UNLOAD');
			setTimeout(()=>{
				this.disconnectMqtt();
			},200)
			clearInterval(this.tmrHeartBeat);
			if(this.player){
				this.player.dispose();
			}
			
			this.stop();
		},
		beforeDestroy() {
			
		},
		onShow(){
 
		},
		onNavigationBarButtonTap(event) {
			if (event.text == '设置') {
				this.fpSensitivity = this.jetsonInfo.fpSensitivity;
				this.showPopup = true;
			}
		},
		methods: {
			initMap() {
			  AMapLoader.load({
				key: "99974f7ec174da94209c9565e24c6a48", // 申请好的Web端开发者Key，首次调用 load 时必填
				version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
				plugins: ["AMap.Scale", "AMap.ToolBar", "AMap.ControlBar", 'AMap.Geocoder', 'AMap.Marker',
				  'AMap.CitySearch', 'AMap.Geolocation', 'AMap.AutoComplete', 'AMap.InfoWindow'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
			  }).then((AMap) => {
				// 获取到作为地图容器的DOM元素，创建地图实例
				this.map = new AMap.Map("AMapContainer", { //设置地图容器id
				  resizeEnable: true,
				  viewMode: "2D", // 使用3D视图
				  zoomEnable: true, // 地图是否可缩放，默认值为true
				  dragEnable: true, // 地图是否可通过鼠标拖拽平移，默认为true
				  doubleClickZoom: true, // 地图是否可通过双击鼠标放大地图，默认为true
				  zoom: 17, //初始化地图级别
				  showBuildingBlock:true, // 是否出现建筑模型
				  pitch:55,    // 视角控制
				})
			  }).catch(e => {
				console.log(e)
			  })
			},
			createPlayer(){
				// 在适合的生命周期，通过script和link标签引入播放器sdk、css
				this.loadWebPlayerSDK().then(() => {
				  // 如果需要使用自定义组件，打开以下注释
				  this.player = new Aliplayer({
				    id: "aliyunVideo",
				    source: this.aliyunVideoUrl.artcUrl,
					rtsFallbackSource:this.aliyunVideoUrl.flvUrl,
				    width: "100%",
				    height: "100%",
				  }, function (player) {
				  });
				  // player.one('canplay', function () {
				  //   console.log('canplay', player.tag);
				  //   player.tag.play();
				  // });
				
				}).catch((e) => {
				  console.log("加载播放器SDK失败", e);
				});
			},
			loadWebPlayerSDK() {
			  return new Promise((resolve, reject) => {
			    const s_tag = document.createElement('script'); // 引入播放器js
			    s_tag.type = 'text/javascript';
			    s_tag.src = 'https://g.alicdn.com/apsara-media-box/imp-web-player/2.20.3/aliplayer-min.js';
			    s_tag.charset = 'utf-8';
			    s_tag.onload = () => {
			      resolve();
			    }
			    document.body.appendChild(s_tag);
			    const l_tag = document.createElement('link'); // 引入播放器css
			    l_tag.rel = 'stylesheet';
			    l_tag.href = 'https://g.alicdn.com/apsara-media-box/imp-web-player/2.20.3/skins/default/aliplayer-min.css';
			    document.body.appendChild(l_tag);
			  });
			},
			loadComponent() {
			  return new Promise((resolve, reject) => {
			    const s_tag = document.createElement('script');
			    s_tag.type = 'text/javascript';
			    // 需要先下载组件 js 文件，放到项目 /static/ 目录下
			    // 下载地址：https://github.com/aliyunvideo/AliyunPlayer_Web/blob/master/customComponents/dist/aliplayer-components/aliplayercomponents-1.0.9.min.js
			    s_tag.src = './static/aliplayercomponents-1.0.9.min.js';
			    s_tag.charset = 'utf-8';
			    s_tag.onload = () => {
			      resolve();
			    }
			    document.body.appendChild(s_tag);
			  });
			},
			loadAliyunVideoUrl(){
				return new Promise((resolve,reject)=>{
					piService.queryAliyunVideoUrl().then(res=>{
						console.log('###aliyuvieourl,',res);
						if(res.code==Constant.SUCCESS){
							
							this.aliyunVideoUrl=res.data;
							resolve();
						}else{
							reject('err');
						}
					}).catch(err=>{
						reject(err);
					})
				})
				
			},
			createJxController(){
 
				let options = {
					zone: document.getElementById('aliyunVideo'),
					//mode: 'static',
					position: {left: '50%', top: '50%'},
					color: 'blue',
					threshold: 20.0,
					size:120
				}
				
				let managerJx = nipplejs.create(options);
				
				managerJx.on('move', (evt, data)=>{
					console.log('角度:'+data.angle.degree+",距离:"+data.distance);
					// left:0,right:1,up:2,down:3
	 
					this.sendCmd(Constant.Protocol.CMD_MOVE_CAMERA,{
						'direction':data.angle.degree,
						'speed':data.distance
					});
					
				})
				
				managerJx.on('start', (evt, data)=>{
					console.log('###start');
				})
				
				managerJx.on('end', (evt, data)=>{
					console.log('###end');
				})
			},
			createController(){
				if(this.manager!=null){
					uni.showToast({
						title:"控制器已经创建",  
						duration:2000,  
						icon:"none"
					})
					return;
				}
				let options = {
					zone: document.getElementById('controllerZone'),
					mode: 'static',
					position: {left: '50%', top: '50%'},
					color: 'red',
					threshold: 20.0,
					size:160
				}
				
				this.manager = nipplejs.create(options);
				
				this.manager.on('move', (evt, data)=>{
					console.log('角度:'+data.angle.degree+",距离:"+data.distance);
					let degree = data.angle.degree;
					this.throttle  = data.distance;
	 
					if(degree > 180){
						this.throttle = 0;
						this.angle = 0;
					}else{
						this.angle = degree;
					}
					
					this.sendCmd(Constant.Protocol.CMD_DRIVE_ALL_ANGLE,[Math.floor(this.throttle),Math.floor(this.angle),1,0,0,0]);
				})
				
				this.manager.on('start', (evt, data)=>{
					console.log('###start');
				})
				
				this.manager.on('end', (evt, data)=>{
					console.log('###end');
					this.angle=0;
					this.throttle=0;
					this.sendCmd(Constant.Protocol.CMD_DRIVE_ALL_ANGLE,[this.throttle,this.angle,0,0,0,0]);
				})
			},
			destroyController(){
				if(this.manager){
					this.manager.off('start');
					this.manager.off('end');
					this.manager.off('move');
					this.manager.destroy();
					console.log('##销毁控制器成功!');
					this.manager = null;
				}
			},
			disconnectMqtt(){
				if(this.client.connected){
					this.client.end(true,()=>{
						this.destroyController();
						uni.showToast({
							title:"断开成功",  
							duration:2000,  
							icon:"none"  
						})
					})
				}
			},
			start(){
				this.sendCmd(Constant.Protocol.CMD_SHIFT_CONTROL_MODE,1);
				
				this.animation.translateY(40).step();
				this.animationData = this.animation.export();
				this.createController();
				setTimeout(()=>{
					this.destroyController();
					this.createController();
				},1000)
				
				
				
			},
			stop(){
				this.sendCmd(Constant.Protocol.CMD_SHIFT_CONTROL_MODE,0);
				
				this.animation.translateY(0).step();
				this.animationData = this.animation.export();
				setTimeout(()=>{
					this.destroyController();
				},1000)
			},
			servo(){
				this.sendCmd(Constant.Protocol.CMD_SERVO_MOTOR_CONTROL,!this.shipInfo?.servoMotorDirection);
			},
			camera(on){
				if(on){					
					this.sendCmd(Constant.Protocol.CMD_OPEN_RTMP,{});	
				}else{					
					this.sendCmd(Constant.Protocol.CMD_CLOSE_RTMP,{});
				}				
			},
			lock_fp(){
				if(this.jetsonInfo?.tracking==1){
					this.sendCmd(Constant.Protocol.CMD_UNTRACK_FP,{});
				}else{
					this.sendCmd(Constant.Protocol.CMD_TRACK_FP,{});
				}
			},
			rod_up(){
				this.sendCmd(Constant.Protocol.CMD_ROD_UP_DOWN,{});
			},
			fish_wire_status(fish_wire_status){
				this.sendCmd(Constant.Protocol.CMD_FISH_WIRE,{
					'fish_wire_status':fish_wire_status
				});
			},
			fish_wire_show(){
				//this.sendCmd(Constant.Protocol.CMD_FISH_WIRE,{});
				this.popShowFishWire = true;
			},
			fpSliderGragEnd(){
				console.log('##sensitivity,',this.fpSensitivity);
				this.sendCmd(Constant.Protocol.CMD_SET_FP_SENSITIVITY,this.fpSensitivity);
			},
			handleSwitchAutoFishChange(data){
				console.log('##switchautofish:',data.value);
				this.sendCmd(Constant.Protocol.CMD_AUTO_FISH,{'auto':data.value});
				
			},
			handleClose_PopupFishWire(){
				this.fish_wire_status(0);
			},
			sendCmd(cmd,data){
				let sendData = {
					cmd: cmd,
					data: data
				};
				this.client.publish(this.cmdTopic,JSON.stringify(sendData));
			}
		}
	}
</script>

<style lang="scss">

	.start {
		.status {
			color:green;
		}
	}
	
	.pd{
		margin-left:10px;
		margin-right:10px ;
	}
	
	.pgs{
		width:100px;
		margin-right: 5px;
	}
	
	.ctl-wrapper{
		text-align: center;
		.ctl{
			height:200px;
			width:200px;
			border-radius: 100px;
			background-color:transparent;
			position: relative;
			display:inline-block;
		}
	}
	
	
	.container {
	    height: 100%;
	    position: relative;
	    padding-bottom: 50px; /* 保证内容不会被底部组件遮挡 */
	  }
	  .fixed-footer {
	    position: fixed;
	    left: 0;
	    bottom: 0;
	    width: 100%;
		height:90px;
	    text-align: center;
	  }

	.video-ctr{
		height: 300px;
	}
	
	.channel-data{
		.channel-value{
			padding-left: 15px;
		}
	}
	
	.fish_wire_wrapper{
		padding:10px;
	}
</style>
